import axios from 'axios'
import Setting from '@/setting';

const apiUrl = Setting.request.apiEsBaseURL;
const apiBaseUrl = Setting.request.apiBaseURL;
const apiCommonUrl = Setting.request.apiCommonBaseURL;

// 【修复】动态获取 token 的函数，而不是在文件加载时获取
function getToken() {
  const token = sessionStorage.getItem("access_token");
  console.log("--esManage.js--get tongyi token---" + token);
  return token;
}

//获取iframe父页面传递来的专家领域数据
function getParentMsgData(parameter) {
  let data = {
    researchFields: parameter.researchFields
  }
  if (parameter && !!parameter.addFieldFlag) {
    try {
      let researchFields = window.localStorage.getItem('researchFields');
      data.researchFieldNames = JSON.parse(researchFields);
    } catch (err) {
      console.log(err)
    }
  }
  if (window._CONFIG.GW_SHOW_YB_DATA) {
    data = {
      ...data,
      showYbData: window._CONFIG.GW_SHOW_YB_DATA
    };
  }
  console.log("config",data)
  return data
}

//post
export function postAction(url, parameter) {
  // 获取统一平台的 access_token
  return axios({
    url: apiUrl + url,
    method: 'post',
    data: {...parameter, ...getParentMsgData(parameter)},
    headers: {
      'Content-Type': 'application/json;charset=UTF-8',
      "token": getToken()  // 【修复】动态获取 token
    }
  })
}

//get
export function getAction(url) {
  return axios({
    url: apiUrl + url,
    method: 'get',
    headers: {
      'Content-Type': 'application/json;charset=UTF-8',
      "token": getToken()  // 【修复】动态获取 token
    }
  })
}
//post
export function commonPostAction(url, parameter) {
  return axios({
    url: apiCommonUrl + url,
    method: 'post',
    data: parameter,
    headers: {
      'Content-Type': 'application/json;charset=UTF-8',
      "token": getToken()  // 【修复】动态获取 token
    }
  })
}
//post
export function commonGetAction(url, parameter) {
  return axios({
    url: apiCommonUrl + url,
    method: 'get',
    data: parameter,
    headers: {
      'Content-Type': 'application/json;charset=UTF-8',
      "token": getToken()  // 【修复】动态获取 token
    }
  })
}

//stream
// 在您的api/esManage.js中修改或添加
export const postStreamAction = (url, params, onMessage, onComplete, onError) => {
  const controller = new AbortController();
  if (window._CONFIG.GW_SHOW_YB_DATA) {
    params = {
      ...params,
      showYbData: window._CONFIG.GW_SHOW_YB_DATA
    };
  }

  const promise = new Promise(async (resolve) => {
    try {
      const response = await fetch(apiUrl + url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'text/event-stream',
          'Cache-Control': 'no-cache',
          'X-Requested-With': 'fetch',
          'token': getToken(),  // 【修复】动态获取 token
        },
        body: JSON.stringify(params),
        signal: controller.signal
      });
      if (!response.ok) throw new Error(`HTTP ${response.status}`);

      const reader = response.body.getReader();
      const decoder = new TextDecoder('utf-8');

      let buffer = '';
      let eventDataLines = []; // 累积当前事件的多行 data:
      let fullContent = '';

      const flushEvent = () => {
        if (eventDataLines.length === 0) return;
        const data = eventDataLines.join('\n');
        eventDataLines = [];
        fullContent += data;
        onMessage && onMessage(data);
      };

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        buffer += decoder.decode(value, { stream: true });

        // 兼容 \r\n，统一换行符
        buffer = buffer.replace(/\r\n/g, '\n');

        // 按行解析；SSE 以空行分隔事件
        let nl;
        while ((nl = buffer.indexOf('\n')) >= 0) {
          const line = buffer.slice(0, nl);
          buffer = buffer.slice(nl + 1);

          if (line === '') {
            // 事件边界
            flushEvent();
            continue;
          }
          if (line.startsWith(':')) {
            // 注释/心跳
            continue;
          }
          if (line.startsWith('data:')) {
            eventDataLines.push(line.slice(5).trim());
          }
          // 可选处理 id:/event: 行：按需存储
        }
      }
      // 流结束，flush 残留
      flushEvent();

      onComplete && onComplete();
      resolve(fullContent);
    } catch (err) {
      if (err.name !== 'AbortError') {
        console.error('SSE error:', err);
        onError && onError(err);
      }
    }
  });

  return { promise, abort: () => controller.abort() };
};

export function httpAction(url, parameter) {
  return axios({
    url: apiUrl + url,
    method: 'post',
    data: parameter,
    headers: {
      'Content-Type': 'application/json;charset=UTF-8',
      "token": getToken()  // 【修复】动态获取 token
    }
  })
}
export function httpBaseAction(url, parameter) {
  return axios({
    url: apiBaseUrl + url,
    method: 'post',
    data: parameter
  })
}


/**
 * 文件上传 用于富文本上传图片
 * @param url
 * @param parameter
 * @returns {*}
 */
export function uploadAction(url, parameter) {
  return axios({
    url: apiUrl + url,
    data: parameter,
    method: 'post',
    headers: {
      'Content-Type': 'multipart/form-data', // 文件上传,,
      "token": getToken()  // 【修复】动态获取 token
    }
  })
}

//下载流附件
export const downloadData = (url, params, fileName) => {
  axios.post(apiCommonUrl + url, params,
    {
      responseType: 'blob'
    }
  ).then(res => {
    let fileDownload = require('js-file-download');
    fileDownload(res.data, fileName);
  })
}
